package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.mongo.PeachBlossomApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.PeachBlossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class PeachBlossomApiImpl implements PeachBlossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 发送传音
     *
     * @return
     * @param peachBlossom
     */
    @Override
    public void add(PeachBlossom peachBlossom) {
        long timeMillis = System.currentTimeMillis();
        peachBlossom.setCreated(timeMillis);
        mongoTemplate.insert(peachBlossom);
    }

    /**
     *           接收传音
     * @param userInfo
     * @return
     */
    @Override
    public PeachBlossom getSound(UserInfo userInfo, List<String> ids) {
        Query query = new Query(Criteria.where("gender").ne(userInfo.getGender()).and("userId").ne(userInfo.getId()));
        query.with(Sort.by(Sort.Order.desc("created")));
        if (CollUtil.isNotEmpty(ids)){
            query.addCriteria(Criteria.where("_id").nin(ids));
        }
        PeachBlossom one = mongoTemplate.findOne(query, PeachBlossom.class);
        return one;
    }


}